<!--
  @Descripttion:用户中心-账号设置（修改手机号）
  @Author：yejianbo
  @Date：2022年05月26日 12:35:40
-->
<template>
  <div class="content-page">
    <div class="content-block">
      <div class="content-title">手机变更</div>
      <div class="main-item">
        <div class="tips-text">
          *修改后，请使用新的手机号登录数据学徒，当前手机号无法再登录数据学徒实习平台。
        </div>
        <div class="row">
          <div class="left">当前手机号码</div>
          <div class="right">
            <!-- 脱敏展示 -->
            <div class="old-phone">{{ formData.oldPhone | hideNum }}</div>
          </div>
        </div>
        <div class="row">
          <div class="left">新手机号码</div>
          <el-select
            v-model="formData.prexNum"
            style="width: 145px; margin-right: 12px"
          >
            <el-option
              v-for="(item, index) in nationPhoneNumber"
              :key="index"
              :value="item.phone_code"
              :label="'+' + item.phone_code"
            >{{ item.chinese_name }}</el-option>
          </el-select>
          <el-input
            v-model="formData.newPhone"
            type="text"
            maxlength="11"
            style="width: 213px; font-size: 20px; top: -2px"
            @blur="checkParams('newPhone')"
          />
          <div v-if="rules.newPhone" class="error-msg">请输入新手机号</div>
        </div>
        <div class="row">
          <div class="left">图形验证码</div>
          <el-input
            v-model="formData.imgCode"
            type="text"
            maxlength="10"
            style="
              width: 213px;
              height: 49px;
              vertical-align: middle;
              font-size: 20px;
            "
            @blur="checkParams('imgCode')"
          />
          <img
            v-imgError
            class="code-img"
            :src="codeImgUrl"
            alt=""
            @click="getCode"
          >
          <div class="resend" @click="getCode">换一张</div>
          <div v-if="rules.imgCode" class="error-msg">请输入图形验证码</div>
        </div>

        <el-form
          ref="userForm"
          :model="userForm"
          :rules="rulesForm"
          label-width="188px"
          style="text-align: left"
        >
          <el-form-item label="姓名" prop="applyUserName">
            <el-input
              v-model="userForm.applyUserName"
              v-maxLenght="18"
              style="width: 50%"
              placeholder="姓名"
            />
          </el-form-item>
          <el-form-item label="身份证号码" prop="cardNo">
            <el-input
              v-model="userForm.cardNo"
              v-maxLenght="18"
              style="width: 50%"
              placeholder="身份证号码"
            />
          </el-form-item>
          <el-form-item
            label="身份证正面"
            prop="authenticationFrontPictureUrl"
            required
          >
            <imageUpload
              v-model="userForm.authenticationFrontPictureUrl"
              :show-tip="false"
            />
          </el-form-item>
          <!-- <p>{{ userForm.authenticationFrontPictureUrl }}</p> -->
          <el-form-item
            label="身份证反面"
            prop="authenticationBackPictureUrl"
            required
          >
            <imageUpload
              v-model="userForm.authenticationBackPictureUrl"
              :show-tip="false"
            />
          </el-form-item>
          <!-- <p>{{ userForm.authenticationBackPictureUrl }}</p> -->
        </el-form>
        <div class="row">
          <div class="left">短信验证码</div>
          <el-input
            v-model="formData.msgCode"
            type="text"
            maxlength="11"
            style="
              width: 213px;
              height: 49px;
              vertical-align: middle;
              font-size: 20px;
            "
            @blur="checkParams('msgCode')"
          />
          <el-button
            :disabled="msgDisabled"
            size="medium"
            style="margin: 0 10px; position: relative; height: 34px"
            type="primary"
            @click.native="handleMsg"
          >{{ count ? count : "发送短信" }}</el-button>
          <div v-if="rules.msgCode" class="error-msg">请输入短信验证码</div>
        </div>
        <div
          v-if="isAdmin"
          class="row"
          style="height: auto; align-items: flex-start; margin-top: 12px"
        >
          <div class="left">在职证明</div>
          <imageUpload v-model="formData.dataUrl" :show-tip="false" />
          <div v-if="rules.dataUrl" class="error-msg">请上传在职证明</div>
        </div>
        <div v-if="isAdmin" class="row">
          <div class="left" />
          <p>
            *由于此账号为企业管理员账号，为保障账号的安全性，需要上传企业相关证明文档或与平台管理员进行联系
          </p>
        </div>
      </div>
      <!-- todo 修改学生手机号，是否添加图形验证码 -->
      <div class="btns" @click="confirmHandle">确定修改</div>
    </div>

    <!-- 阿里认证弹窗 -->
    <div v-if="showAuthentication" class="showAuthentication">
      <div class="showAuthenticationBox">
        <div class="title">实名认证</div>
        <div v-loading="showLoading" class="content">
          {{ authenticationTitle }}
        </div>
        <div class="btns">
          <div class="cancel" @click="showAuthentication = false">取消</div>
          <div
            v-if="isAdmin || !isAdmin && authenticationTitle === '认证成功'"
            class="submit"
            @click="getMsgFun"
          >
            确定
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getImgCode,
  updateCompanyUserInfo,
  changeCompanyPhone,
  sendMsgCode,
  isRealName
} from '@/api/company-admin-api/userManage'
import { getIsAdmin } from '@/api/company-admin-api/hireManage/index.js'
import { nationPhoneNumber } from '@/utils/frontDataDict.js'
import { mapMutations } from 'vuex'
import { getPath } from '@/utils/ruoyi'
import ImageUpload from '@/components/ImageUpload'
import { mapGetters } from 'vuex'

export default {
  // 组件名称
  name: 'SetAccount',
  filters: {
    hideNum(num = '') {
      return num.substring(0, 3) + '****' + num.substring(7, 11)
    }
  },
  components: { ImageUpload },
  // 组件状态值
  data() {
    return {
      isChangeing: false,
      msgDisabled: false,
      showAuthentication: false,
      showLoading: true,
      authenticationTitle: '',
      nationPhoneNumber: nationPhoneNumber,
      userForm: {
        applyUserName: '', // 企业申请人姓名
        authenticationFrontPictureUrl: '', // 身份证正面
        authenticationBackPictureUrl: '', // 身份证反面
        cardNo: '' // 身份证号码
      },
      rulesForm: {
        applyUserName: [
          {
            required: true,
            message: '企业申请人姓名不能为空',
            trigger: 'blur'
          }
        ],
        cardNo: [
          {
            required: true,
            message: '申请人身份证号码不能为空',
            trigger: 'blur'
          }
        ],
        authenticationFrontPictureUrl: [
          { required: true, message: '身份证正面不能为空', trigger: 'change' }
        ],
        authenticationBackPictureUrl: [
          { required: true, message: '身份证反面不能为空', trigger: 'change' }
        ]
      },
      formData: {
        prexNum: '86', // 手机区号
        oldPhone: '', // 旧手机
        newPhone: '', // 新手机
        imgCode: '', // 图形验证码
        msgCode: '', // 短信验证码
        dataUrl: '' // 证明材料
      },
      uuid: '',
      rules: {
        newPhone: false,
        imgCode: false,
        msgCode: false,
        dataUrl: false
      },
      codeImgUrl: '',
      timeInstance: null,
      count: null,
      loading: false,
      isAdmin: false
    }
  },

  computed: {
    ...mapGetters(['companyInfo'])
  },
  watch: {
    'formData.newPhone'(newValue) {
      if (newValue.length > 20) {
        this.formData.newPhone.splice(0, 20)
      }
    },
    companyInfo() {
      if (this.companyInfo.authorizedStatus === 'changeing') {
        this.isChangeing = true
        this.formData.newPhone = localStorage.getItem('newPhone')
        const { dataUrl, ...newData } = JSON.parse(
          localStorage.getItem('oldPhoneData')
        )
        this.formData.dataUrl = dataUrl
        this.userForm = newData
      } else {
        this.isChangeing = false
        localStorage.getItem('oldPhoneData') &&
        localStorage.removeItem('oldPhoneData')
        localStorage.getItem('newPhone') && localStorage.removeItem('newPhone')
      }
    }
  },
  created() {
    this.formData.oldPhone = localStorage.getItem('companyLoginPhone')
    if (this.companyInfo.authorizedStatus === 'changeing') {
      this.isChangeing = true
      this.formData.newPhone = localStorage.getItem('newPhone')
      const { dataUrl, ...newData } = JSON.parse(
        localStorage.getItem('oldPhoneData')
      )
      console.log(dataUrl, newData, this.companyInfo, '---')
      this.formData.dataUrl = dataUrl
      this.userForm = newData
    } else {
      this.isChangeing = false
      localStorage.getItem('oldPhoneData') &&
        localStorage.removeItem('oldPhoneData')
      localStorage.getItem('newPhone') && localStorage.removeItem('newPhone')
    }
    this.getCode()
    this.getIsAdmin()
  },
  // 组件方法
  methods: {
    ...mapMutations(['loginOut']),
    getIsAdmin() {
      getIsAdmin().then((res) => {
        if (res.code === 0 && res.data) {
          this.isAdmin = true
        }
      })
    },
    getMsgFun() {
      if (this.isChangeing) {
        this.$message.warning('已提交审核，请等待～')
        return
      }
      const param = {
        code: this.formData.imgCode,
        mobile: this.formData.prexNum + '-' + this.formData.newPhone,
        scene: 4,
        uuid: this.uuid
      }
      this.showAuthentication = false
      sendMsgCode(param)
        .then((res) => {
          if (res.code === 0 && res.data) {
            if (this.timeInstance !== null) {
              clearInterval(this.timeInstance)
            }
            this.count = 59
            this.msgDisabled = true
            this.timeInstance = setInterval(() => {
              this.count--
              if (this.count <= 0) {
                clearInterval(this.timeInstance)
                this.count = null
                this.timeInstance = null
                this.msgDisabled = false
              }
            }, 1000)
          } else {
            this.getCode()
            clearInterval(this.timeInstance)
            this.count = null
            this.timeInstance = null
            this.msgDisabled = false
          }
        })
        .catch(() => {
          this.getCode()
          clearInterval(this.timeInstance)
          this.count = null
          this.timeInstance = null
          this.msgDisabled = false
        })
    },
    handleMsg() {
      console.log('userForm>>', this.userForm)
      if (this.isChangeing) {
        this.$message.warning('已提交审核，请等待～')
        return
      }
      if (this.formData.newPhone === this.formData.oldPhone) {
        this.$message.warning('不可修改为相同手机号')
        return
      }
      if (!this.checkParams('newPhone') && !this.checkParams('imgCode')) {
        if (this.msgDisabled) return
        this.$refs.userForm.validate((boo) => {
          if (boo) {
            this.showLoading = true
            this.showAuthentication = true
            isRealName({
              cardNo: this.userForm.cardNo,
              phone: this.formData.newPhone,
              userName: this.userForm.applyUserName
            })
              .then((res) => {
                this.showLoading = false
                const { code, message } = res.data
                if (Number(code) === 1) {
                  this.authenticationTitle = '认证成功'
                } else {
                  this.authenticationTitle = message || '认证失败'
                }
              })
              .catch((err) => {
                this.authenticationTitle = '认证失败'
                this.showLoading = false
              })
          }
        })
      }
    },
    checkParams(key) {
      switch (key) {
        case 'newPhone':
          if (/^[0-9]{1,}/.test(this.formData.newPhone)) {
            this.rules.newPhone = false
          } else {
            this.rules.newPhone = true
          }
          break
        case 'imgCode':
          if (this.formData.imgCode !== '') {
            this.rules.imgCode = false
          } else {
            this.rules.imgCode = true
          }
          break
        case 'msgCode':
          if (/^[0-9]{1,}/.test(this.formData.msgCode)) {
            this.rules.msgCode = false
          } else {
            this.rules.msgCode = true
          }
          break
        case 'dataUrl':
          if (this.formData.dataUrl !== '') {
            this.rules.dataUrl = false
          } else {
            this.rules.dataUrl = true
          }
          break
      }
      return this.rules[key]
    },
    getCode() {
      getImgCode().then((res) => {
        if (res.data) {
          res.data.img = 'data:image/jpeg;base64,' + res.data.img
          this.codeImgUrl = res.data.img
          this.uuid = res.data.uuid
        }
      })
    },
    confirmHandle() {
      if (this.isChangeing) {
        this.$message.warning('已提交审核，请等待～')
        return
      }
      if (
        !this.checkParams('newPhone') &&
        !this.checkParams('imgCode') &&
        !this.checkParams('msgCode')
      ) {
        if (this.isAdmin && this.checkParams('dataUrl')) {
          return
        }
        if (this.loading) return
        this.submit()
      }
    },
    submit() {
      let param = {
        code: this.formData.msgCode,
        newMobile: this.formData.newPhone,
        oldMobile: this.formData.oldPhone,
        scene: 4,
        dataUrl: '',
        authStatus: this.authenticationTitle // 三要素认证结果，纯文本，在后台直接展示
      }
      if (this.isAdmin) {
        param.dataUrl = this.formData.dataUrl
        param = Object.assign(param, this.userForm)
        this.$confirm('请注意，更换手机号后，需要运营平台进行审核，审核期间新、旧手机号均无法登录，是否提交手机号变更审核?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          changeCompanyPhone(param)
            .then((res) => {
              this.loading = false
              if (res.code === 0 && res.data) {
                this.userForm.dataUrl = this.formData.dataUrl
                localStorage.setItem('oldPhoneData', JSON.stringify(this.userForm))
                localStorage.setItem('newPhone', this.formData.newPhone)
                this.$store.dispatch('LogOut').then(() => {
                  this.$message.success('账户修改申请成功，请重新登录')
                  location.href = getPath('/#/login')
                })
              }
            })
            .catch((e) => {
              this.loading = false
            })
        })
      } else {
        if (this.authenticationTitle !== '认证成功') {
          this.$message.warning('实名认证三要素未通过，请重试')
          return
        }
        this.loading = true
        /**
         * 企业子账号要调用更新企业用户的接口，不要用上面的企业管理员更新接口【changeCompanyPhone】，
         * 【changeCompanyPhone】会更新企业用户+企业2张表
         * 【updateCompanyUserInfoInfo】只更新企业用户本身,且只更新手机号、姓名
         */
        const CompanyUserParams = {
          nickname: this.userForm.applyUserName, // 姓名
          mobile: this.formData.newPhone // 新手机号
        }
        updateCompanyUserInfo(CompanyUserParams)
          .then((res) => {
            this.loading = false
            if (res.code === 0 && res.data) {
              this.userForm.dataUrl = this.formData.dataUrl
              localStorage.setItem('oldPhoneData', JSON.stringify(this.userForm))
              localStorage.setItem('newPhone', this.formData.newPhone)
              this.$store.dispatch('LogOut').then(() => {
                this.$message.success('账户修改申请成功，请重新登录')
                location.href = getPath('/#/login')
              })
            }
          })
          .catch((e) => {
            this.loading = false
          })
      }
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.content-page {
  position: relative;
  width: 100%;
  padding: 40px;
  overflow-y: auto;
  .showAuthentication {
    position: fixed;
    z-index: 2014;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.3);
    .showAuthenticationBox {
      width: 360px;
      height: 241px;
      padding: 66px 30px 90px;
      border-radius: 12px;
      background: #fff;
      position: relative;
      .content {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 15px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383d;
        line-height: 21px;
      }
      .content2 {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 15px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383d;
        line-height: 21px;
      }
      .title {
        position: absolute;
        width: 100%;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #37383d;
        line-height: 25px;
        top: 25px;
      }
      .title2 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383d;
        line-height: 20px;
        margin-bottom: 12px;
      }
      .btns {
        width: 100%;
        height: 40px;
        position: absolute;
        bottom: 40px;
        left: 0;
        display: flex;
        justify-content: space-between;
        padding: 0 40px;
        & > div {
          width: 130px;
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          font-size: 14px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #4677b9;
          border: 1px solid #4677b9;
          border-radius: 2px;
          cursor: pointer;
          &.submit {
            background: #4677b9;
            color: #fff;
            border: none;
          }
        }
      }
    }
  }
  .content-block {
    position: relative;
    width: 100%;
    min-width: 1000px;
    min-height: calc(100vh - 67px);
    margin: 0 auto;
    background: #fff;
    position: relative;
    .content-title {
      font-size: 36px;
      font-weight: 600;
      color: #37383d;
      line-height: 50px;
      margin-bottom: 10px;
    }
    .explan-content {
      width: 180px;
      height: 210px;
      font-size: 24px;
      color: #37383d;
      line-height: 33px;
      text-align: center;
      margin-top: 15px;
    }
    .main-item {
      display: flex;
      flex-direction: column;
      margin-left: 20px;
      .item-title {
        font-size: 28px;
        color: #37383d;
        line-height: 40px;
      }
      .tips-text {
        font-size: 20px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fc9c21;
        line-height: 28px;
      }
    }
    .row {
      position: relative;
      height: 49px;
      line-height: 49px;
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 12px;
      .left {
        min-width: 188px;
        max-width: 188px;
        text-align: left;
        line-height: 49px;
        font-size: 23px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383d;
      }
      .right {
        flex: 1;
        .old-phone {
          position: relative;
          font-size: 20px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #37383d;
        }
      }
      .code-img {
        display: inline-block;
        width: 147px;
        height: 49px;
        margin: 0 15px 0 13px;
        cursor: pointer;
      }
      .resend {
        min-width: 100px;
        font-size: 23px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #54cf52;
        height: 49px;
        line-height: 49px;
        cursor: pointer;
      }
      .error-msg {
        position: relative;
        font-size: 23px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fc9c21;
        height: 49px;
        line-height: 49px;
        margin-left: 30px;
        padding-left: 21px;
        min-width: 206px;
        &::before {
          content: "";
          display: block;
          width: 16px;
          height: 16px;
          background: url("../../../assets/images/user/error.png") no-repeat
            center center / cover;
          position: absolute;
          left: 0;
          top: 50%;
          margin-top: -8px;
        }
      }
    }
    .btns {
      position: relative;
      width: 464px;
      height: 60px;
      margin: 0 auto;
      background: #4677b9;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 20px;
      font-weight: 600;
      color: #ffffff;
      cursor: pointer;
      margin-top: 25px;
      &:first-child {
        margin-right: 60px;
      }
      &:hover {
        color: #2f8efe;
        box-shadow: 0px 4px 15px 0px rgba(0, 0, 0, 0.08);
      }
    }
  }
  ::v-deep .el-input--suffix .el-input__inner {
    font-size: 20px;
  }
  ::v-deep .el-form-item__label {
    text-align: left;
    font-size: 23px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #37383d;
    display: inline-flex;
    align-items: center;
    height: 49px;
    &::before {
      display: none;
    }
  }
  ::v-deep .el-form-item {
    margin-bottom: 12px;
    width: 100%;
  }
  ::v-deep .el-form-item__content {
    margin: 0 !important;
    width: 730px;
  }
  ::v-deep .el-input--medium {
    display: flex;
    align-items: center;
    height: 49px;
  }
}
</style>
